package com.server.controller;

import com.common.constant.JwtClaimsConstant;
import com.common.properties.JwtProperties;
import com.common.result.Result;
import com.common.utils.JwtUtil;
import com.pojo.dto.UserDTO;
import com.pojo.entity.User;
import com.pojo.vo.UserVO;
import com.server.service.UserInfoService;
import com.server.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户接口")
public class UserController {
    /*
    * 登录和注册
    * 前端数据发送username和password,包装为User对象
    * */

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    UserInfoService userInfoService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserVO> login(@RequestBody UserDTO userDTO){
        log.info("用户登录:{}",userDTO);
        User user = userService.login(userDTO);
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        UserVO userVO = UserVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token).build();

        return Result.success(userVO);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result register(@RequestBody UserDTO userDTO){
        log.info("用户注册");
        Integer userId = userService.register(userDTO);
        //当用户注册成功时，自动生成默认用户信息
        userInfoService.insertUserInfo(userId);
        return Result.success();
    }



}
